<?php
session_start();
include("includes/session.php");
if(isset($_COOKIE['itt'])){
	$username = $_COOKIE['itt']['username'];
	$password = md5($_COOKIE['itt']['password']);
	$query = mysql_query("SELECT * FROM `user` WHERE `username` = '$username' AND password = '$password' AND `status` = '1'");
	$login_rs = mysql_fetch_object($query);
	if(mysql_num_rows($query)){
		$_SESSION['loggedin'] = 1;
		if($login_rs->report[0] == 1){
			checkReport();
		}
		header('Location: index?'); 
		exit();
	}
}
if (isset($_GET['error']) AND !empty($_GET['error'])){ 
	?>
	<script>alert('Sai toàn khoản/mật khẩu hoặc tài khoản đã bị khóa!');window.history.back(-1);</script>
	<?
}
if(isset($_POST['login'])){
	$url = $_REQUEST['url'];
	$username = $_POST['username'];
	$password = md5($_POST['password']);
	$time = time();
	$check = $_POST['setcookie'];
	$query = mysql_query("SELECT * FROM `user` WHERE `username` = '$username' AND password = '$password' AND `status` = '1'");
	if(mysql_num_rows($query)){
		$rs = mysql_fetch_object($query);
		$_SESSION['loggedin'] = 1;
		$_SESSION['loginid'] = $rs->id;
		$_SESSION['fullname'] = $rs->fullname;
		$_SESSION['username'] = $rs->username;
		$visited = date('Y-m-d h:i:s', time());
		mysql_query("UPDATE `user` SET `lastvisited` = '$visited' WHERE `id` = '$rs->id'");
		if($check){
			setcookie("itt[loginid]", $_SESSION['loginid'], $time + 3600);
			setcookie("itt[username]", $username, $time + 3600);
			setcookie("itt[password]", $password, $time + 3600);
		}
		if($rs->report[0] == 1){
			checkReport();
		}
		header("Location: $url"); 
		exit();
	}
	else{
		header('Location: index?menu=login&error=1'); 
		exit(); 
	}
}
$itt->assign("tittle", "Đăng nhập");
$itt->display('templates/login.tpl');
?>